<?php

use console\db\Migration;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Console;

/**
 * 初始化类型数据
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m200110_001120_d_staff_test extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%staff}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        if (!$this->isExistsTable($this->tableName)) {
            return false;
        }
        $this->truncateTable($this->tableName);
        $this->compact = true;
        $data = $this->getData('staff.dev.php');
        $count = count($data);
        Console::startProgress($i = 0, $count);
        /* @var $security \common\base\Security */
        $security = Yii::$app->security;
        foreach ($data as $item) {
            list($companyId, $provinceCompany, $cityCompanyName, $companyName, $realname, $mobile) = $item;
            $uniMobile = $security->generatePrivateKey($mobile);
            $hasStaff = (new Query())->from($this->tableName)->andWhere(['mobile' => $uniMobile])->exists();
            if ($hasStaff) {
                continue;
            }
            $query = (new Query())->from('{{%company}}');
            $query->select('id');
            $query->andWhere([
                'and',
                ['name' => $provinceCompany],
                ['parent_id' => 0],
            ]);
            $parentCid = $query->scalar();

            if (!$companyId) {
                $query = (new Query())->from('{{%company}} a');
                $query->select('a.id');
                $query->innerJoin('{{%company}} p', 'a.parent_id=p.id');
                $query->andWhere([
                    'p.name' => $cityCompanyName,
                    'p.parent_id' => $parentCid,
                    'a.name' => $companyName,
                ]);
                $companyId = $query->scalar();
            }
            $this->insert($this->tableName, [
                'realname' => $realname,
                'mobile' => $uniMobile,
                'mobile_hash' => $security->encryptMaster($mobile),
                'company_id' => intval($companyId),
                'status' => 0,
                'created_at' => time(),
                'updated_at' => time(),
            ]);
            $i++;
            Console::updateProgress($i, $count);
        }
        Console::endProgress("update done." . PHP_EOL);
        $this->resetAutoIncrement('{{%staff}}', 1000, true);
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        if (!$this->isExistsTable($this->tableName)) {
            return false;
        }
        $this->truncateTable($this->tableName);
    }

}
